//
//  AccessToken.swift
//  WeiBo_NB
//
//  Created by apple on 15/3/6.
//  Copyright (c) 2015年 Ai. All rights reserved.
//

import UIKit

class AccessToken: NSObject ,NSCoding{
   
    
    // MARK:- access_token相关属性
    ///  用于调用access_token，接口获取授权后的access token。
    var access_token : String?
    
  ///  access_token的生命周期，单位是秒数。
    var expires_in:NSNumber?{
        didSet{
           expiresDate = NSDate(timeIntervalSinceNow: expires_in!.doubleValue)
            println("过期日期 \(expiresDate)")

        }
    }
    
    ///  token过期日期
    var expiresDate: NSDate?
    
    /// 是否过期－用过期日期和当前时间进行比较
    var isExpired: Bool {
        return expiresDate?.compare(NSDate()) == NSComparisonResult.OrderedAscending
    }
    
    ///声明周期（ 即将废弃）
    var remind_in: NSNumber?
    
    ///  当前授权用户的UID，可以通过这个 id 获取用户的进一步信息
    var uid : Int = 0
    
    
    
    // MARK:- 沙盒存取的相关方法
     init(dict:NSDictionary) {
        super.init()
        self.setValuesForKeysWithDictionary(dict as [NSObject : AnyObject])
    }

    ///  将数据写入沙盒
    func saveAccessToken(){
        NSKeyedArchiver.archiveRootObject(self, toFile: AccessToken.tokenPath())
    }
    ///  从沙盒中读取数据
    class func loadAccessToken() -> AccessToken?{
        return NSKeyedUnarchiver.unarchiveObjectWithFile(AccessToken.tokenPath()) as? AccessToken
    }
    
    ///   Path路径
     class func tokenPath()->String{
        var path = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last as!String
        path = path.stringByAppendingPathComponent("WeiBoToken.plist")
        return path
    }
    
    ///  归档方法
     func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(access_token)
        aCoder.encodeObject(expiresDate)
        aCoder.encodeInteger(uid, forKey: "uid")
    }
    ///  解档方法
     required init(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObject() as? String
        expiresDate = aDecoder.decodeObject() as? NSDate
        uid = aDecoder.decodeIntegerForKey("uid")
    }
    
}
///  格式化输出
extension AccessToken: DebugPrintable {
    
    override var debugDescription: String {
        let dict = self.dictionaryWithValuesForKeys(["access_token", "expiresDate", "uid"])
        return "\(dict)"
    }
}



